package com.fenghuo.utils;

import android.content.Context;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class UtilLocation extends AsyncTask<Void, Map<Double, Double>, Void> {

    private OnlocationUpdateListener listener;
    private LocationManager locationManager;
    private GpsStatus gpsStatus;
    private String curentpstr;
    private Location currentLocation;//当前location
    private boolean cancle = false;
    private Criteria criteria;

    public UtilLocation(Context context) {
        locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

        //创建一个Criteria对象
        criteria = new Criteria();
        //设置粗略精确度
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        //设置是否需要返回海拔信息
        criteria.setAltitudeRequired(false);
        //设置是否需要返回方位信息
        criteria.setBearingRequired(false);
        //设置是否允许付费服务
        criteria.setCostAllowed(true);
        //设置电量消耗等级
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        //设置是否需要返回速度信息
        criteria.setSpeedRequired(false);
        //curentpstr=locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
        curentpstr = locationManager.getBestProvider(criteria, true);
    }

    @Override
    protected void onPreExecute() {
        //根据当前provider对象获取最后一次位置信息
        currentLocation = locationManager.getLastKnownLocation(curentpstr);
        //如果位置信息为null，则请求更新位置信息
        if (currentLocation == null) {
            try {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpslocationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, netLocationListener);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //增加GPS状态监听器
        locationManager.addGpsStatusListener(gpsListener);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Map<Double, Double>... values) {
        super.onProgressUpdate(values);
        Double latitude = values[0].get(0);
        Double longtitude = values[0].get(1);
        if (listener != null)
            listener.update(latitude, longtitude);
    }

    @Override
    protected void onPostExecute(Void result) {

        super.onPostExecute(result);
    }

    @Override
    protected Void doInBackground(Void... params) {
        //直到获得最后一次位置信息为止，如果未获得最后一次位置信息，则显示默认经纬度
        //每隔10秒获取一次位置信息
        while (!cancle) {
            currentLocation = locationManager.getLastKnownLocation(curentpstr);
            if (currentLocation != null) {
                Log.d("Location", "Latitude: " + currentLocation.getLatitude());
                Log.d("Location", "location: " + currentLocation.getLongitude());
                HashMap<Double, Double> map = new HashMap<Double, Double>();
                map.put(0d, currentLocation.getLatitude());
                map.put(1d, currentLocation.getLongitude());
                publishProgress(map);
                break;
            } else {
                Log.d("Location", "Latitude: " + 0);
                Log.d("Location", "location: " + 0);
                HashMap<Double, Double> map = new HashMap<Double, Double>();
                map.put(0d, 0d);
                map.put(1d, 0d);
                publishProgress(map);
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                cancle = true;
                Log.e("Location", e.getMessage());
            }
        }
        return null;
    }

    //-------------------- GpsStatus.Listener
    private GpsStatus.Listener gpsListener = new GpsStatus.Listener() {

        @Override
        public void onGpsStatusChanged(int event) {
            //获取当前状态
            gpsStatus = locationManager.getGpsStatus(null);
            switch (event) {
                //第一次定位时的事件
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    break;
                //开始定位的事件
                case GpsStatus.GPS_EVENT_STARTED:
                    break;
                //发送GPS卫星状态事件
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    Iterable<GpsSatellite> allSatellites = gpsStatus.getSatellites();
                    Iterator<GpsSatellite> it = allSatellites.iterator();
                    int count = 0;
                    while (it.hasNext()) {
                        GpsSatellite satellite = it.next();
                        //satellite.
                    }
                    break;
                //停止定位事件
                case GpsStatus.GPS_EVENT_STOPPED:
                    Log.d("Location", "GPS_EVENT_STOPPED");
                    break;
            }
        }

    };

    //-----------------locationlistener----创建位置监听器----------

    //一：gps
    private LocationListener gpslocationListener = new LocationListener() {

        boolean isremove = false;

        //位置发生改变时调用
        @Override
        public void onLocationChanged(Location location) {
            Log.d("gpslocationListener", "onLocationChanged");
            if (location != null && !isremove) {
                locationManager.removeUpdates(netLocationListener);
                isremove = true;
            }
        }

        //状态改变时调用
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("gpslocationListener", "onStatusChanged");
            if (LocationProvider.OUT_OF_SERVICE == status) {
                Log.d("gpslocationListener", "GPS服务丢失,切换至网络定位");
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, netLocationListener);
            }
        }

        //provider启用时调用
        @Override
        public void onProviderEnabled(String provider) {
            Log.d("gpslocationListener", "onProviderEnabled");

        }

        //provider失效时调用
        @Override
        public void onProviderDisabled(String provider) {
            Log.d("gpslocationListener", "onProviderDisabled");

        }
    };

    //二：net
    private LocationListener netLocationListener = new LocationListener() {
        // 位置发生改变时调用
        @Override
        public void onLocationChanged(Location location) {
            Log.d("netLocationListener", "onLocationChanged");
        }

        // 状态改变时调用
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d("netLocationListener", "onStatusChanged");

        }

        // provider启用时调用
        @Override
        public void onProviderEnabled(String provider) {
            Log.d("netLocationListener", "onProviderEnabled");

        }

        // provider失效时调用
        @Override
        public void onProviderDisabled(String provider) {
            Log.d("netLocationListener", "onProviderDisabled");

        }
    };
    //--------------------方法

    /**
     * 位置更新接口
     *
     * @author Administrator
     */
    public abstract interface OnlocationUpdateListener {
        void update(Double latitude, Double longtitude);
    }

    public void setOnLocationupdatelistener(OnlocationUpdateListener listener) {
        this.listener = listener;
    }
}
